package com.example.tasks;

import com.example.jobtask.service.HotPlugContextService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 示例热插拔任务：使用第三方库
 * 演示如何在热插拔任务中使用Spring容器中的Bean和第三方库
 */
public class ThirdPartyLibTask {
    
    /**
     * 使用Jackson进行JSON处理
     */
    public String processJson() {
        try {
            HotPlugContextService contextService = HotPlugContextService.getInstance();
            
            // 从Spring容器获取ObjectMapper Bean
            ObjectMapper objectMapper = contextService.getBean(ObjectMapper.class);
            
            // 创建测试数据
            Map<String, Object> data = new HashMap<>();
            data.put("taskName", "ThirdPartyLibTask");
            data.put("executeTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            data.put("status", "success");
            data.put("count", 100);
            
            // 转换为JSON字符串
            String jsonString = objectMapper.writeValueAsString(data);
            
            // 解析JSON字符串
            JsonNode jsonNode = objectMapper.readTree(jsonString);
            
            String message = String.format("JSON处理成功:\n原始数据: %s\nJSON字符串: %s\n解析后任务名: %s",
                data.toString(), jsonString, jsonNode.get("taskName").asText());
            
            System.out.println("[ThirdPartyLibTask] " + message);
            return message;
            
        } catch (Exception e) {
            String errorMsg = "JSON处理失败: " + e.getMessage();
            System.err.println("[ThirdPartyLibTask] " + errorMsg);
            return errorMsg;
        }
    }
    
    /**
     * 使用RestTemplate进行HTTP请求
     */
    public String makeHttpRequest() {
        try {
            HotPlugContextService contextService = HotPlugContextService.getInstance();
            
            // 从Spring容器获取RestTemplate Bean（需要先配置）
            RestTemplate restTemplate;
            try {
                restTemplate = contextService.getBean(RestTemplate.class);
            } catch (Exception e) {
                // 如果没有配置RestTemplate Bean，创建一个新的
                restTemplate = new RestTemplate();
            }
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("User-Agent", "JobTask-HotPlug/1.0");
            
            HttpEntity<String> entity = new HttpEntity<>(headers);
            
            // 发送GET请求到一个公共API（这里使用httpbin.org作为示例）
            String url = "https://httpbin.org/json";
            ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.GET, entity, String.class);
            
            String message = String.format("HTTP请求成功:\nURL: %s\n状态码: %s\n响应体: %s\n请求时间: %s",
                url, response.getStatusCode(), response.getBody(),
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            
            System.out.println("[ThirdPartyLibTask] " + message);
            return message;
            
        } catch (Exception e) {
            String errorMsg = "HTTP请求失败: " + e.getMessage();
            System.err.println("[ThirdPartyLibTask] " + errorMsg);
            return errorMsg;
        }
    }
    
    /**
     * 综合示例：从数据库获取数据并通过HTTP发送
     */
    public String syncDataToRemote() {
        try {
            HotPlugContextService contextService = HotPlugContextService.getInstance();
            
            // 1. 从数据库获取用户统计数据
            Map<String, Object> userStats = contextService.queryForMap(
                "SELECT COUNT(*) as total_users, " +
                "SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as active_users " +
                "FROM job_sys_user"
            );
            
            // 2. 使用Jackson转换为JSON
            ObjectMapper objectMapper = contextService.getBean(ObjectMapper.class);
            
            Map<String, Object> syncData = new HashMap<>();
            syncData.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            syncData.put("source", "job-task-system");
            syncData.put("data", userStats);
            
            String jsonData = objectMapper.writeValueAsString(syncData);
            
            // 3. 通过HTTP发送数据（这里使用httpbin.org的POST接口作为示例）
            RestTemplate restTemplate;
            try {
                restTemplate = contextService.getBean(RestTemplate.class);
            } catch (Exception e) {
                restTemplate = new RestTemplate();
            }
            
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json");
            headers.set("User-Agent", "JobTask-HotPlug/1.0");
            
            HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
            
            String url = "https://httpbin.org/post";
            ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.POST, entity, String.class);
            
            String message = String.format("数据同步成功:\n发送数据: %s\n响应状态: %s\n同步时间: %s",
                jsonData, response.getStatusCode(),
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            
            System.out.println("[ThirdPartyLibTask] " + message);
            return message;
            
        } catch (Exception e) {
            String errorMsg = "数据同步失败: " + e.getMessage();
            System.err.println("[ThirdPartyLibTask] " + errorMsg);
            return errorMsg;
        }
    }
    
    /**
     * 使用Spring的其他服务
     */
    public String useSpringServices() {
        try {
            HotPlugContextService contextService = HotPlugContextService.getInstance();
            
            // 获取自定义的Service Bean
            Object sysUserService = contextService.getBean("sysUserService");
            
            String message = String.format("成功获取Spring服务: %s, 类型: %s, 获取时间: %s",
                "sysUserService", sysUserService.getClass().getSimpleName(),
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            
            System.out.println("[ThirdPartyLibTask] " + message);
            return message;
            
        } catch (Exception e) {
            String errorMsg = "获取Spring服务失败: " + e.getMessage();
            System.err.println("[ThirdPartyLibTask] " + errorMsg);
            return errorMsg;
        }
    }
}